﻿using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using System.Text;


namespace Dropthings.Widget.Widgets.CnWeather
{
    public class WeatherStateCach
    {
        private static WeatherStateCach instance = new WeatherStateCach();

        public static WeatherStateCach Instance
        {
            get
            {
                return instance;
            }
        }

        private string filePah = string.Empty;
        public string FilePath
        {
            get
            {
                if (string.IsNullOrEmpty(filePah))
                {
                    string fileName = "/App_Data/WeatherStateCach.xml";
                    filePah = System.Web.HttpContext.Current.Server.MapPath(fileName);
                }
                return filePah;
            }
        }

        public string XmlSerializationWeather(string[] items)
        {
            var xmlSerialization = new XmlSerializer(typeof(string[]));
            using (Stream stream = new MemoryStream())
            {
                using (var xtWriter = new XmlTextWriter(stream, Encoding.UTF8))
                {
                    xmlSerialization.Serialize(xtWriter, items);
                    xtWriter.Flush();
                    stream.Seek(0, SeekOrigin.Begin);
                    using (var reader = new StreamReader(stream, Encoding.UTF8))
                    {
                        string response = reader.ReadToEnd();
                        return response;
                    }
                }
            }
        }

        public void SaveWeatherSate(string[] items)
        {
            try
            {
                string xmltext = XmlSerializationWeather(items);
                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.LoadXml(xmltext);
                xmlDocument.Save(FilePath);
            }
            catch {     }
        }

        public string[] DeSerializeWeather()
        {

            var xmlSerialization = new XmlSerializer(typeof(string[]));
            using (FileStream fileStream = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                using (var xmlReader = new XmlTextReader(fileStream))
                {
                    var items = xmlSerialization.Deserialize(xmlReader) as string[];

                    return items;
                }
            }

        }
    }
}
